package com.yu.task;

import java.util.concurrent.*;

public class CompletableFutureDemo {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1,Integer.MAX_VALUE,60, TimeUnit.SECONDS,new SynchronousQueue<>());        //异步调用 无返回值
//        CompletableFuture<Void> cf = CompletableFuture.runAsync(()->{
//            System.out.println(Thread.currentThread().getName() + "异步调用");
//        });
//        cf.get();
//        //异步调用 有返回值
//        CompletableFuture<Integer> cf2 = CompletableFuture.supplyAsync(()->{
//            return 10/0;
//        });
//
//        cf2.whenComplete((t,u)->{ //这里的t 是返回值结果  u是异常信息
//            System.out.println(t);
//            System.out.println(u);
//        });
        //这就是异步编排
        CompletableFuture.supplyAsync(()->{ //第一个异步
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return 1;
        }).thenApply(f -> { //第二个异步
            return f+2;
        }).whenComplete((v,e)->{//结果
            if (e==null){
                System.out.println("result:" + v);
            }
        }).exceptionally(e->{
            e.printStackTrace();
            return null;
        });
        //主线程睡眠三秒，不然主线程结束后，上面异步的线程也会关闭
        TimeUnit.SECONDS.sleep(3);
        System.out.println("main over");
        threadPoolExecutor.shutdown();

    }
}
